const fs = require('fs')
const path = require('path')

// 在这里定义年份和月份
const year = 2024
const month = 10

// 去除 YAML 前后文块
function removeYamlFrontMatter(content) {
  return content.replace(/---\s*[\s\S]*?\s*---\s*/, '')
}

const date = new Date()

// 合并相同年月的周报到月报文件中
function generateMonthlyReports(year = date.getFullYear(), month = date.getMonth() + 1) {
  const WEEKLY_REPORTS_DIR = path.join(__dirname, '周报')
  const MONTHLY_REPORTS_DIR = path.join(__dirname, '月报')

  // 创建月报目录（如果不存在）
  if (!fs.existsSync(MONTHLY_REPORTS_DIR)) {
    fs.mkdirSync(MONTHLY_REPORTS_DIR)
  }

  const files = fs.readdirSync(WEEKLY_REPORTS_DIR)
  const monthlyReports = {}

  files.forEach(file => {
    const match = file.match(/(\d{4})年(\d{1,2})月第\d周周报\.md/)
    if (match) {
      const fileYear = parseInt(match[1], 10)
      const fileMonth = parseInt(match[2], 10)

      if (fileYear === year && fileMonth === month) {
        const key = `${year}-${month}`
        const weeklyReportPath = path.join(WEEKLY_REPORTS_DIR, file)
        let weeklyContent = fs.readFileSync(weeklyReportPath, 'utf-8')
        weeklyContent = removeYamlFrontMatter(weeklyContent)
        if (!monthlyReports[key]) {
          monthlyReports[key] = ''
        }

        monthlyReports[key] += `# ${file}\n\n${weeklyContent}\n\n`
      }
    }
  })

  Object.keys(monthlyReports).forEach(key => {
    const [year, month] = key.split('-')
    const monthlyReportPath = path.join(MONTHLY_REPORTS_DIR, `${year}年${month}月月报.md`)
    fs.writeFileSync(monthlyReportPath, monthlyReports[key])
    console.log(`Monthly report generated: ${monthlyReportPath}`)
  })

  if (Object.keys(monthlyReports).length === 0) {
    console.log(`No weekly reports found for ${year}年${month}月.`)
  }
}

// 生成月报
// generateMonthlyReports(year, month)
generateMonthlyReports()
